package com.shiyang.prototype.deepclone;

import java.io.*;

/**
 * @author shiyang date: 2020/9/9
 */
public class DeepProtoType implements Serializable, Cloneable {

    private String name; // String属性
    private DeepCloneableTarget deepCloneableTarget; // 引用类型

    public DeepProtoType() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }

    // 深拷贝 - 方式1 使用 clone 方法
    @Override
    protected DeepProtoType clone() throws CloneNotSupportedException {
        DeepProtoType deep = null;
        // 这里完成对基本数据类型(属性)和String属性的克隆
        deep = (DeepProtoType)super.clone();
        // 对应用类型的属性 进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType)deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget)deepCloneableTarget.clone();
        return deep;
    }

    // 深拷贝 - 方式二 通过对象的序列化实现 (推荐)
    public DeepProtoType deepClone() {
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this); // 当前这个对象以对象流的方式输出

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType)ois.readObject();

            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String toString() {
        return "DeepProtoType{" + "name='" + name + '\'' + ", deepCloneableTarget=" + deepCloneableTarget + '}';
    }
}
